/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.common;

import com.mxg.blog.service.UserService;

/**
 * @Author: ycq_work@163.com
 * @DATE: 2023/6/23 23:00
 * 判断是否登录
 */
public class DetermineLogin {
    private String requestMapUserAccount;
    private static volatile DetermineLogin instance;

    // 登录状态
    public static final Integer NOT_LOGIN = -1;
    public static final Integer YES_LOGIN = 1;

    // 配置userService
    private UserService userService;

    private final RegularExpression regularExpression = new RegularExpression();
    private final CqLogger cqLogger = CqLogger.getInstance();

    // 设置含参构造方法
    DetermineLogin(String requestMapUserAccount)
    {
        this.requestMapUserAccount = requestMapUserAccount;
    }

    // 创建类
    public static DetermineLogin getInstance(String requestMapUserAccount, UserService userService) {
        if (instance == null) {
            synchronized (DetermineLogin.class) {
                if (instance == null) {
                    instance = new DetermineLogin(requestMapUserAccount);
                }
            }
        }
        instance.setRequestMap(requestMapUserAccount);
        instance.setUserService(userService);
        return instance;
    }

    // 设置参数
    private void setRequestMap(String requestMapUserAccount) {
        this.requestMapUserAccount = requestMapUserAccount;
    }

    private void setUserService(UserService userService) {
        this.userService = userService;
    }

    // 判断是否为空
    private boolean judgeIsEmpty(String requestMapUserAccount){
        return requestMapUserAccount == null;
    }

    // 判断账号是否存在
    private Integer determineWhetherUserAccount(String requestMapUserAccount){
        if(regularExpression.isEmail(requestMapUserAccount))
        {
            if(userService.getUserByUserEmail(requestMapUserAccount).getId() != null){
                return userService.getUserByUserEmail(requestMapUserAccount).getId();
            }else {
                return NOT_LOGIN;
            }
        }else if(regularExpression.isPhoneNum(requestMapUserAccount)){
            if(userService.getUserByUserPhoneNum(requestMapUserAccount).getId() != null){
                return userService.getUserByUserPhoneNum(requestMapUserAccount).getId();
            }else{
                return NOT_LOGIN;
            }
        }else {
            return NOT_LOGIN;
        }
    }

    // 启动方法
    public Integer startJudge(){
        if(judgeIsEmpty(requestMapUserAccount)){
            cqLogger.print("该用户名不存在");
            return NOT_LOGIN;
        }else if(determineWhetherUserAccount(requestMapUserAccount) != -1){
            return determineWhetherUserAccount(requestMapUserAccount);
        }else {
            cqLogger.print("该用户名不存在");
            return NOT_LOGIN;
        }
    }
}
